const mysql = require('mysql2/promise'),
      log   = console.log,
      Koa   = require('koa'),
      app   = new Koa(),
      Router = require('koa-router'),
      router = new Router(),
      fs    = require('fs'),
      path  = require('path'),
      cors  = require('koa2-cors'),
      http  = require('http'),
      https = require('https'),
      body = require('koa-bodyparser'),
      hq = require('./comments.js'),
      gohttp = require('gohttp'),
      request = require('request');
      //moment = require('moment');

const options = {
    key:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.key')),
    cert:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.crt'))
}
app.use(body());
app.use(cors({
    origin: function (ctx) {
        if (ctx.url === '/test') {
          return "*"; // 允许来自所有域名请求
        }
        return 'http://localhost:8080'; // 这样就能只允许 http://localhost:8080 这个域名的请求了 
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
//顺序
function sortx(a,b){
  return b.date-a.date;
}
//反序
function sortj(a,b){
  return Date.parse(a.date)-Date.parse(b.date);
}
//id筛选
function food(data,id){
    for(var i = 0;i < data.length;i++){
       if(data[i].food!=id){
           data.splice(i,1);
              i-=1;
       }
    }
    return data;
}
//删空
function climg (obj, fn) {
  for (var i in obj) {
      if (typeof obj[i] === 'object') {
            climg(obj[i], fn)
      }
      if (fn(obj[i])) {
          delete obj[i]
      }
  }
}
 
function delimg (foo) {
    if (typeof foo === 'object') {
        for (var i in foo) {
             return false
        }
        return true
    } else {
        return foo === '' || foo === null || foo === undefined
    }
}
//调用 climg(imgs,delximg) 

function time(date){
    t1=date;
    t2=new Date().getTime();
    t = t2 -t1;
    //console.log(t);
    if(t<60*1000) return '刚刚';
    else if(t<3600*1000){ 
        t=(t-t%60000)/60000;
        return t+'分钟前';
    }
    else if(t<24*3600*1000){
        t=(t-t%3600000)/3600000;
        return t+'小时前';
    }
    else if(t<365*24*3600*1000){
        t=(t-t%86400000)/86400000;
        return t+'天前';
    }
    else if(t>365*24*3600*1000){
        t=(t-t%31536000000)/31536000000;
        return t+'年前';
    }
}


router.post('/comments',async (ctx)=>{
  log(ctx.request.body);
  let share_id = ctx.request.body.share_id;
  let user_id = ctx.request.body.user_id;
  let date = ctx.request.body.date;
  let text = ctx.request.body.text;
  log(share_id,user_id,date,text);
  const requestPromise = new Promise((resolve,reject) => {
    if(share_id!=undefined&&user_id!=undefined&&date!=undefined&&text!=undefined){
      let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxa9d0987bf6537b82&secret=b3ff596bd138b55e50ff547ba8412105`;
      request(url,function(error,response,body){
        let token = JSON.parse(body).access_token;
        let urljc = `https://api.weixin.qq.com/wxa/msg_sec_check`
                   + `?access_token=${token}`;
        //console.log(urljc)
        let data = {"content":`${text}`}
        let data1 = JSON.stringify(data) 
        console.log(data1)
        abc = httprequest(urljc,data1);
        function httprequest(urljc,data1){
          request({
            url: urljc,
            method: "POST", 
            headers: {
              "content-type": "application/json",
            },
            body: data1
          }, function(error, response, body) {
            if (!error && response.statusCode == 200) {
              let body1 = JSON.parse(body)
              console.log(body1) // 请求成功的处理逻辑
              if(body1.errcode === 0){
                hq.insertcomments(share_id,user_id,date,text); 
                arr = 0;  
              }
              else if(body1.errcode === 87014) arr = 1;
              else arr = 2; 
              console.log(arr);
              //ctx.body =JSON.stringify(arr);
              return resolve({
                arr
              });
            }
          });
        };
      });
    }
  })
  
  const result = await requestPromise;
  console.log(result);
  ctx.body = JSON.stringify(result);
  
})

router.post('/comments/shuju',async (ctx)=>{
  log(ctx.request.body);
  let share_id = ctx.request.body.share_id;
  let user_id = ctx.request.body.user_id;
  let arr;
  if(share_id!=undefined){
    arr = await hq.getid_comments(share_id);
    arr = arr.sort(sortx);
    len = arr.length;
    for(let i=0;i<len;i++) arr[i].date=time(arr[i].date);
    for(let i = 0;i < len;i++){
      let brr = await hq.get_state(user_id,arr[i].id);
      console.log(brr);
      if(brr.length == 0) arr[i].state ='0';
      else arr[i].state = brr[0].state;
    }
    console.log(arr)
    ctx.body = JSON.stringify(arr);
  }
})

router.get('/zan',async (ctx)=>{
  let {comments_id,user_id,state} = ctx.request.query;
  let arr = await hq.get_state(user_id,comments_id);
  let brr = await hq.getid_zan(comments_id);
  let state1;
  if(arr.length==0) {
    hq.insert_state(user_id,comments_id,1);
    hq.zannum(comments_id,Number(brr[0].zan)+1);
    state1 = '1';
  }
  else{
    if(arr[0].state==1){
      hq.zannum(comments_id,Number(brr[0].zan)-1);
      hq.updatezan(user_id,comments_id,0); 
      state1 = '0';
    }
    else if(arr[0].state==0){
      hq.zannum(comments_id,Number(brr[0].zan)+1);
      hq.updatezan(user_id,comments_id,1);
      state1 = '1';
    }
  }
  let crr = await hq.getid_zan(comments_id);
  crr[0].state = state1;
  console.log(crr);
  ctx.body = JSON.stringify(crr);
})

process.on('unhandledRejection',(reason,p) => {
    console.log('Unhandled Rejection at:Promise',p,'reason:',reason);
});

app.use(router.routes())
   .use(router.allowedMethods());
//app.listen(2227);


https.createServer(options,app.callback()).listen(2744);

